$(function(){
    var win = window;
	var cms=window.cms=window.cms||{
	};
	var seller=cms.seller={};
	var service=cms.service={};
	var render=cms.render={};

	var handler=cms.handler={};
	var util = cms.util = {};

    var server = win.server = {};
    var sellerId = 0;

    //图片类型
	var uploadImgType = win.uploadImgType = {
		especially:"f9",
        food:"f9",
		interaction:"f9",
		scenic:"f9"
	};

	util.cmsBox = function(data,type,opts,flag){
		var title = opts["title"] || "CMS_BOX" ;
		var root = $("#cms_box").fadeIn();
		var title = root.find(".t").text(title) ;
		var content = root.find(".c").empty() ;
		var cls = root.find(".cls").on("click",function(){
			root.fadeOut() ;		
		}) ;
		var typeHooks = {
			"photo_list" : function(data){
				var photoListWrap = $("<div class='photo-list-wrap'></div>").appendTo(content) ;
				var photoContent = $("<div class='photo-content'></div>").appendTo(photoListWrap) ;
				//var imageUrl = "http://203.100.80.150/img/" ;
				$.each(data,function(i,item){
					var photoInfo = $("<div class='photo-info'></div>").appendTo(photoContent) ;
					var delIcon = $("<span class='close'>X</span>").attr("id",item["id"])
					.appendTo(photoInfo)
					.on("click",function(){
						$.ajax({ 
						 	url : "/jybb-upload/image/delete.json?imageId=" + delIcon.attr("id") ,
						   	type : "GET" ,
						    dataType: "json" ,
						    success:function(data){
						    	photoInfo.remove() ;
						    } ,
					        error:function(){
					        	alert("图片删除失败!") ;
					        }
				 		}) ;
					}) ;console.log(item)
					var photoIcon = $("<div class='icon'></div>").appendTo(photoInfo) ;
					var photoImage = $("<img width='320' height='240' />")
					//.attr("src",imageUrl + item["imageDirName"] + "/" + item["imageName"])
                    .attr("src", "http://" + item["imageDirName"] + ".oss-cn-beijing.aliyuncs.com/" + item["imageName"])
					.appendTo(photoIcon) ;
					var photoName = $("<div class='name'></div>").appendTo(photoInfo) ;
					if(true === flag){
						photoName.text("序号1：") ;
						var sortEdit = $("<input class='sort-edit' type='text' />").val(item["sortBy"]).appendTo(photoName) ;
						var descEdit = $("<input type='text' />");
						descEdit.val(item["imageDesc"]).appendTo(photoName);
						var editButt = $("<a href=''>确定</a>")
						.appendTo(photoName)
						.on("click",function(e){
							var imageData = {
									"imageId":""+item["id"],
									"imageDesc":encodeURI(descEdit.val()),
									"imageSortBy":sortEdit.val()
							};
							console.log(descEdit);
							$.ajax({ 
							 	url :"/jybb-upload/image/addDesc.json",
							   	type : "POST" ,
							    dataType: "json" ,
							    data : JSON.stringify(imageData) ,
							    success:function(result){
							    	alert("图片信息编辑成功!") ;
							    } ,
						        error:function(){
						        	alert("图片信息编辑失败!") ;
						        }
					 		}) ;
							e.preventDefault() ;
						}) ;
					}
					else{
						var radioIconButt = $("<a href='' class='radio-icon-button'>设为封面</a>")
						.appendTo(photoName)
						.on("click",function(e){
							$("#imageId").data("imgId",item["id"]) ;
							root.hide() ;
							var iconRoot = $("#iconView").fadeIn() ;
							iconRoot.find("img").attr("src",item["imageUrl"]) ;
							e.preventDefault() ;
						}) ;
					}
				}) ;
			}
		} ;

		var hooks = typeHooks[type] ;
		if(hooks){
			hooks(data) ;
		}
		else{
			throw new Error("无效的参数类型：" + "<" + type + ">") ;
		}

	} ;


	seller.roomWrap=function(){
		$('#roomBtn').on('click',function(){
			$('#seeRoom').show();
		})

		$('#seeRoom .cls').on('click',function(){
			$('#seeRoom').hide();
		})
	}

	cms.seller.roomWrap();

	seller.roomShow=function(){
		$('.room').die().live('click',function(){
			var roomPK=$(this).parent().attr('roompk');
			cms.service.getRoomDetail(roomPK).done(function(data){
				console.log(data);
				render.renderRoomDetail(data['result']);
				cms.service.roomImgFile($('#addRoom').attr('roompk'));
			})
			$('#roomDetails').show();

			$('#buttons input').show();
			$('#buttons input').eq(3).hide();
		})
		
		$('#closeroomDetailsBg').on('click',function(){
			$('#roomDetails').hide();
		})

		$('#addRoomBtn').on('click',function(e){
			$('#roomDetails').show();
			$('#roomDetails .input-text').val('');
			$('#roomFacility input').attr('checked',false);
			$('#buttons input').hide();
			$('#buttons input').eq(3).show();
		})

		$('#customWrapBtn').on('click',function(){
			$('#customWrap').show();
			cms.render.customPrice(parseInt($('#addRoom').attr('roompk')));
			$('#roomDetails').hide();
		})

		$('#closeCustom').on('click',function(){
			$('#customWrap').hide();
			$('#roomDetails').show();
		})
	}

	cms.seller.roomShow();

	seller.contractShow=function(){
		$('#contractBtn').on('click',function(){
			$('#contractDetail').show()
			cms.service.getContract().done(function(data){
				console.log(data)
				if(data['code']=='200'){
					cms.render.contract(data['result']);
				}
				var i=0;
				$('.line input').each(function(i,list){
					if($('.line input').eq(i).val()){
						i++
						console.log(i);
					}else{
						i--
						console.log(i);
					}
					if(i>=0){
						$('#addContract').hide();
						$('#changeContract').show();
						$('#removeContract').show();
						return false
					}else{
						// console.log(1)
						$('#addContract').show();
						$('#changeContract').hide();
						$('#removeContract').hide();
						return false
					}
					
				})
			})

		})

		$('#closeContract').on('click',function(){
			$('#contractDetail').hide()
		})
	}

	cms.seller.contractShow();

	seller.maskShow=function(){
		$(window).on('scroll',function(){
            var scrollTop = $(window).scrollTop();
            if(scrollTop>50){
                $('.finsihed-butt').show();
                $('.topFixeBg').show();
            }else if(scrollTop<50){
                $('.finsihed-butt').hide();
                $('.topFixeBg').hide();
            }
        })
	}
	cms.seller.maskShow()

	seller.roomFlag=function(btn,flag){
		$(btn).on('click',function(){
			var FacilityArr=[];
			var roomFacilityInput=$("#roomFacility input:checked").each(function(){
				FacilityArr.push($(this).val());
			});
			var roomFacility=FacilityArr.join('-');
			
			if(flag==1){
				var submitData={
					sellerId:parseInt(sellerId),
					roomName:$('#roomName').val(),
					roomPrice:parseFloat($('#roomPrice').val()),
					weekendPrice:parseFloat($('#weekendPrice').val()),
					festivalPrice:parseFloat($('#festivalPrice').val()),
					jybbPrice:parseFloat($('#jybbPrice').val()),
					jybbWeekendPrice:parseFloat($('#jybbWeekendPrice').val()),
					jybbFestivalPrice:parseFloat($('#jybbFestivalPrice').val()),
					roomSize:parseInt($('#roomSize').val()),
					doubleBedCount:parseInt($('#doubleBedCount').val()),
					singleBedCount:parseInt($('#singleBedCount').val()),
					roomFacility:roomFacility,
					introduction:$('#introduction').val(),
					bedType:parseInt($('#bedType').val()),
					roomNum:parseInt($('#roomNum').val()),
					holdNum:parseInt($('#holdNum').val()),
					proxyRebate:parseFloat($('#proxyRebate').val()),
					memo:$('#memo').val(),
					payType:$('#payType').val()
				};
				//console.log(submitData);
				cms.service.addRoom(JSON.stringify(submitData)).done(function(data){
					console.log(data);
					alert(data['msg']);
					if(data['code']=='200'){
						$('#closeroomDetailsBg').trigger('click');
						cms.service.getRoomList().done(function(data){
							render.renderRoomList(data);
						})
					}
				}).fail(function(){
					alert('失败');
				});
			}else if(flag=2){
				var submitData={
					roomPk:$('#addRoom').attr('roomPK'),
					sellerId:parseInt(sellerId),
					roomName:$('#roomName').val(),
					roomPrice:parseFloat($('#roomPrice').val()),
					weekendPrice:parseFloat($('#weekendPrice').val()),
					festivalPrice:parseFloat($('#festivalPrice').val()),
					jybbPrice:parseFloat($('#jybbPrice').val()),
					jybbWeekendPrice:parseFloat($('#jybbWeekendPrice').val()),
					jybbFestivalPrice:parseFloat($('#jybbFestivalPrice').val()),
					roomSize:parseInt($('#roomSize').val()),
					doubleBedCount:parseInt($('#doubleBedCount').val()),
					singleBedCount:parseInt($('#singleBedCount').val()),
					roomFacility:roomFacility,
					introduction:$('#introduction').val(),
					bedType:parseInt($('#bedType').val()),
					roomNum:parseInt($('#roomNum').val()),
					holdNum:parseInt($('#holdNum').val()),
					proxyRebate:parseFloat($('#proxyRebate').val()),
					memo:$('#memo').val(),
					payType:$('#payType').val()
				};
				cms.service.changeRoom(JSON.stringify(submitData)).done(function(data){
					alert(data['msg']);
					if(data['code']=='200'){
						
						cms.service.getRoomList().done(function(data){
							render.renderRoomList(data);
						})
					}
				}).fail(function(){
					alert('失败');
				});
			}
		})
	}




	cms.seller.roomFlag('#submitAddRoomBtn',1);
	cms.seller.roomFlag('#submitChangeRoomBtn',2);


	service.addRoom=function(submitData){
		return $.ajax({
			url:'/cms/seller/room/add.ojson',
			type:"POST",
			dataType: "json",
			data:submitData
		})
	}



	seller.removeRoomBtn=function(btn){
		$(btn).die().live('click',function(){
			var roompk={
				roomPk:[parseInt($(this).parent().attr('roomPK'))]
			}
			console.log(JSON.stringify(roompk))
			cms.service.removeRoom(JSON.stringify(roompk)).done(function(data){
				console.log(data);
				alert(data['msg']);
				if(data['code']=='200'){
					
					cms.service.getRoomList().done(function(data){
						render.renderRoomList(data);
					})
				}
			}).fail(function(){
				alert('失败');
			});
		})
	}

	cms.seller.removeRoomBtn('.removeRoom');


	
	service.changeRoom=function(submitData){
		return $.ajax({
			url:'/cms/seller/room/update.ojson',
			type:"POST",
			dataType: "json",
			data:submitData
		})
	}

	service.removeRoom=function(submitData){
		return $.ajax({
			url:'/cms/seller/room/delete.ojson',
			type:"POST",
			dataType: "json",
			data:submitData
		})
	}

	service.getRoomList=function(){
		return $.ajax({
			url:'/cms/seller/room/list.ojson',
			type:"GET",
			dataType: "json",
			data:{
				sellerId:sellerId
			}
		})
	}

	service.getRoomDetail=function(submitData){
		return $.ajax({
			url:'/cms/seller/room/get.ojson',
			type:"GET",
			dataType: "json",
			data:{
				roomPk:submitData
			}
		})
	}

	cms.service.getRoomList().done(function(data){
		render.renderRoomList(data);
	})

	

	//渲染房间列表
	render.renderRoomList=function(data){
		var roomListWrap=$('#yroomListWrap');
		roomListWrap.empty();
		$.each(data['result']['data'],function(i,list){
			var p=$('<p class="room"></p>').html(list['roomName']);
			var span=$('<span class="removeRoom">X</span>');
			var li=$('<li roomPK="'+list["roomPk"]+'" roomPrice="'+list["roomPrice"]+'" festivalPrice="'+list["festivalPrice"]+'"></li>');
			li.append(p);
			li.append(span);
			roomListWrap.append(li);
		})

	}

	render.renderRoomDetail=function(data){
		$('#addRoom').attr('roomPk',data['roomPk']);
		$('#bedType').val(data['bedType']);
		$('#doubleBedCount').val(data['doubleBedCount']);
		$('#festivalPric').val(data['festivalPric']);
		$('#holdNum').val(data['holdNum']);
		$('#introduction').val(data['introduction']);
		$('#jybbFestivalPrice').val(data['jybbFestivalPrice']);

		$('#singleBedCount').val(data['singleBedCount']);

		$('#jybbPrice').val(data['jybbPrice']);
		$('#jybbWeekendPrice').val(data['jybbWeekendPrice']);

		$('#memo').val(data['memo']);
		$('#payType').val(data['payType']);

		$('#roomName').val(data['roomName']);
		$('#roomNum').val(data['roomNum']);
		$('#roomPk').val(data['roomPk']);
		$('#roomPrice').val(data['roomPrice']);
		$('#roomSize').val(data['roomSize']);
		$('#weekendPrice').val(data['weekendPrice']);
		$('#festivalPrice').val(data['festivalPrice']);

		$('#proxyRebate').val(data['proxyRebate']);
		if(data['tagDtoList']){
			$.each(data['tagDtoList'],function(i,list){
				$('#roomFacility input').each(function(i,lists){
					if(parseInt($('#roomFacility input').eq(i).val())===list['id']){
						$(this).attr('checked',true).prop("checked",true);
					}
				})
			})
		}
		
	}


	render.customPrice=function(data){
        return $.ajax({
            url:'/cms/seller/room/customprice/list.ojson?roomPk='+data+'', // FIXME: test data
			type:"GET",
			dataType: "json",
            success:function(resp) {
            	console.log(resp);
                var ulEle = $("#customPriceList > ul");
                ulEle.empty();
                var html = '';
                $.each(resp.result.data, function(i,item){
                    html += '<li>';
                    html += '开始时间：<input type="text" value="' + $.myTime.UnixToDate(item.startDate / 1000) + '" class="startDate"/>';
                    html += '结束时间：<input type="text" value="' + $.myTime.UnixToDate(item.endDate / 1000) + '" class="endDate"/>';
                    html += '价格：<input type="text" value="' + item.roomPrice + '" class="customPrice"/>';
                    html += '<input type="button" class="changeCustomPrice" value="更改" roompricepk=' + item.id + ' />'
                    html += '<input type="button" class="removeCustomPrice" value="删除" roompricepk=' + item.id + ' />'
                    html += '</li>';
                });
                ulEle.append(html);
            }
		})
	}


	// add custom price
	seller.submitCustomPrice=function(btn){
		$('#customPriceBtn').on('click',function(){
			var submitData={
                roomPk:parseInt($('#addRoom').attr('roompk')),//FIXME: test data
				roomPrice:parseFloat($('#addCustomPrice').val()),
				startDate:$('#addStartDate').val(),
				endDate:$('#addEndDate').val()
			}
			service.addCustomPrice(submitData).done(function(data){
				console.log(data);

                render.customPrice(parseInt($('#addRoom').attr('roompk')));
			})

		})
	}
	seller.submitCustomPrice();
	service.addCustomPrice=function(submitData){
		return $.ajax({
			url:'/cms/seller/room/customprice/add.ojson',
			type:"POST",
			dataType: "json",
			data:JSON.stringify(submitData)
		})
	}

    // update custom price

	// update custom price
	seller.changeCustomPriceBtn=function(){
		$('.changeCustomPrice').die().live('click',function(){
			var submitData={
				roomPricePk:$(this).attr('roompricepk'),
				roomPrice:parseFloat($(this).parent().find('.customPrice').val()),
				startDate:$(this).parent().find('.startDate').val(),
				endDate:$(this).parent().find('.endDate').val()
			}
			service.changeCustomPrice(submitData).done(function(data){  
				alert(data['msg']);
                if(data['code']=='200'){
					
					render.customPrice(parseInt($('#addRoom').attr('roompk')));
				}

			})

		})
	}
	
	seller.changeCustomPriceBtn();
	service.changeCustomPrice=function(submitData){
		return $.ajax({
			url:'/cms/seller/room/customprice/update.ojson',
			type:"POST",
			dataType: "json",
			data:JSON.stringify(submitData)
		})
	}

	// delete custom price
	seller.removeCustomPriceBtn=function(){
		$('.removeCustomPrice').die().live('click',function(){
            var roomPricePks = [];
            roomPricePks[0] = $(this).attr('roompricepk');
			var submitData={
                roomPricePk:roomPricePks
			}
			service.removeCustomPrice(submitData).done(function(data){
				alert(data['msg']);
				if(data['code']=='200'){
					
					render.customPrice(parseInt($('#addRoom').attr('roompk')));
				}
			})
		})
	}
	seller.removeCustomPriceBtn();
	service.removeCustomPrice=function(submitData){
		return $.ajax({
			url:'/cms/seller/room/customprice/delete.ojson',
			type:"POST",
			dataType: "json",
			data:JSON.stringify(submitData)
		})
	}


	service.roomImgFile=function(aaaaa){
  		var strategyFile = $("#buttons");
  		var uploadButton = $("#fileImg");
		var viewListButton = $("#seeImg");
	
		viewListButton.on("click",function(e){

			$.ajax({
			 	url :"/jybb-upload/image/list.json?belongId="+parseInt($('#addRoom').attr('roompk'))+"&imageCatalog=f9",
			   	type : "GET" ,
			    dataType: "json" ,
			    success:function(data){
			    	var images = null ;
			    	if("200" === data["code"]){
			    		images = data["result"] ;
			    		cms.util.cmsBox(images,"photo_list",{title:"游记的图片"},true) ;		
			    	}
			    } ,
		        error:function(){
		        	alert("图片列表获取失败!") ;
		        }
	 		}) ;
			e.preventDefault() ;
		}) ;
		
		var uiCon = $("<div class='ui-con'></div>").appendTo(strategyFile) ;
		var iconWrap = $("<div class='icon-wrap'></div>").appendTo(uiCon) ;
		var iconRoot = $("#uploadImgList") ;
		
		var doUploadButt = iconRoot.find(".upload-butt") ;
		
		iconRoot.find(".cls").on("click",function(){
			$(this).parent().fadeOut();
		}) ;
		
  		var imageUploader = new plupload.Uploader({
		    browse_button: "fileImg" ,
		    url: cms.baseUrl +  "/jybb-upload/image/upload.do?belongId="+aaaaa+"&imageCatalog=f9" 
		}) ;
  		
  		imageUploader.init() ;
		
  		
  		imageUploader.bind('FilesAdded', function(up, files){
  			iconRoot.find("ol").empty() ;
			doUploadButt.show() ;
			iconRoot.show("slow") ;
			iconWrap.hide() ;
		    plupload.each(files, function(file) {
		        var li = $("<li style='margin-bottom:10px;'></li>").attr("id",file.id).text(file.name + ' ' + plupload.formatSize(file.size)).appendTo(iconRoot.find('ol'));
		        var delSpan = $("<span style='float:right;margin-right:20px;color:red;cursor:pointer;'>X</span>")
		        .appendTo(li)
		        .on("click",function(){
		        	$(this).parent().remove() ;
		        	if(!iconRoot.find("ol > li").size()){
		        		doUploadButt.hide() ;
		        		iconRoot.hide() ;
		        	}
		        }) ;
		    });
		});

  		imageUploader.bind('Uploa   dProgress', function(up, file) {
            $('#' + file.id + ' > span').text(file.percent);
		});
  		
  		imageUploader.bind('FileUploaded', function(up, file,result) {
  			
  			var fileId = eval(result.response)[0];
  			$.ajax({
			 	url : "/jybb-upload/image/getImgById.json?imageId=" +fileId ,
			   	type : "GET" ,
			    dataType: "json" ,
			    success:function(data){
			    } ,
		        error:function(){
		        	alert("upload file fail") ;
		        }
	 		}) ;
  		
  		});

        imageUploader.bind('UploadComplete', function() {
            iconRoot.hide() ;
            alert('update room image done!');
        });
  		
  		imageUploader.bind('Error', function(up,err) {
		    alert("文件上传发生错误，请重试!") ;
		});
  		
  		uploadButton.on("click",function(){
			
			doUploadButt.on("click",function(){
				
				imageUploader.start() ;
				$(this).unbind("click") ;
			}) ;
		
		}) ;
		
	} ;
	service.roomImgFile();
	//以上是房间的代码





















	//更改服务的显示隐藏
	$('.serviceCheckBox').on('click',function(){
		if($(this).is(':checked')){
			//勾上处理的事
			$('#'+$(this).attr('serviceFlag')).show();
		}else{
			//取消勾选处理的事
			$('#'+$(this).attr('serviceFlag')).hide();
		}
	})

	//适合场景的TAB切换
	$('#tabController button').on('click',function(e){
		e.preventDefault();
		$('#tabView textarea').eq($(this).index()).show().siblings().hide();
		
	})



	var strategyId=20;
	//富文本编辑器
	var editor;
	util.textEditor=function(){
		KindEditor.ready(function(K) {
	        editor = K.create($("#innerContent"), {
	            resizeType : 1,
	            width  : "100%" ,
	            height :"410px" ,
	            allowPreviewEmoticons : false,
	            allowImageUpload : false,
	            items : [
	                'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
	                'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
	                'insertunorderedlist', '|', 'emoticons', 'image', 'link']
	        });
	    });
	}

    var testJybbHost = "http://localhost";
    //多个图片的上传
	server.strategyFile=function(uploadBtn,uploadC,flag){

  		var uploadButton = $("#"+uploadBtn);
		var iconRoot = $("#uploadImgList") ;
		
		var doUploadButt = iconRoot.find(".upload-butt") ;
		
		iconRoot.find(".cls").on("click",function(){
			$(this).parent().fadeOut();
		}) ;
		
  		var imageUploader = new plupload.Uploader({
		    browse_button: uploadBtn ,
		    url:testJybbHost + "/jybb-upload/image2/upload.do"
		}) ;
  		
  		imageUploader.init() ;
		
  		
  		imageUploader.bind('FilesAdded', function(up, files){
  			iconRoot.find("ol").empty() ;
			doUploadButt.show() ;
			iconRoot.show("slow") ;

		    plupload.each(files, function(file) {
		         var li = $("<li style='margin-bottom:10px;'></li>").attr("id",file.id).text(file.name + ' ' + plupload.formatSize(file.size)).appendTo(iconRoot.find('ol'));
		        var delSpan = $("<span style='float:right;margin-right:20px;color:red;cursor:pointer;'>X</span>")
		        .appendTo(li)
		        .on("click",function(){
		        	$(this).parent().remove() ;
		        	if(!iconRoot.find("ol > li").size()){
		        		doUploadButt.hide() ;
		        		iconRoot.hide() ;
		        	}
		        }) ;
		    });
		});

  		/*imageUploader.bind('Uploa   dProgress', function(up, file) {
            $('#' + file.id + ' > span').text(file.percent);
		});*/
  		
  		imageUploader.bind('FileUploaded', function(up, file,result) {
            var resp = JSON.parse(result.response);
  			var imgId = resp.result[0].imageId;
            var imgUrl = resp.result[0].imageUrl;
            if(flag == "1"){ //适合、特点的渲染
                var controlsDiv = $('<div style="float:left;margin-left:10px;position:relative;"></div>').attr('imgid', imgId);
                var img = $('<img style="display:block;width:220px;height:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"/>').attr('src', imgUrl);
                var textarea = $('<textarea></textarea>');
                var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:20px;left:190px;cursor:pointer;">X</strong>');
                handler.bindImageDelete(strong, imgId);
                controlsDiv.append(img);
                controlsDiv.append(textarea);
                controlsDiv.append(strong);
                $(uploadC).append(controlsDiv);
            }else if(flag == '2'){ //互动项目
                var controlsDiv = $('<div style="float:left;margin-left:10px;position:relative;"></div>').attr('imgid', imgId);
                var img = $('<img style="display:block;width:220px;height:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"/>').attr('src',imgUrl);
                var textarea = $('<textarea></textarea>');
                var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:75px;left:190px;cursor:pointer;">X</strong>');
                handler.bindImageDelete(strong, imgId);
                controlsDiv.append(img);
                controlsDiv.append(textarea);
                controlsDiv.append(strong);
                $(uploadC).append(controlsDiv);
            }else if(flag == '3'){ // 餐饮
                var controlsDiv = $('<div style="float:left;margin-right:10px;position:relative;margin-top:10px;">').attr("imgid", imgId);
                var img = $('<img style="display:block;width:220px;height:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"/>').attr('src',imgUrl);
                var inputFoodName = $('<input type="text" placeholder="价格" style="display:block;margin-bottom:10px;"/>');
                var inputFoodPrice = $('<input type="text" placeholder="菜名"/>'); 
                var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:20px;left:190px;cursor:pointer;">X</strong>');
                handler.bindImageDelete(strong, imgId);
                controlsDiv.append(img);
                controlsDiv.append(strong);
                controlsDiv.append(inputFoodName);
                controlsDiv.append(inputFoodPrice);
                $(uploadC).append(controlsDiv);
            }else if(flag == '4'){ //商家图片
                var controlsDiv = $('<div style="float:left;margin-right:10px;position:relative;margin-top:10px;">').attr("imgid", imgId);
                var input = $('<input type="button" value="设置为头图" class="btn btn-success" />');
                input.on('click', function() { // bind set frontcover action
                    $.ajax({
                        url : "/cms20/seller/sellerimage/setfrontcover.ojson?imgId" + imgId,
                        type : "GET",
                        headers : {"devicetype":2},
                        success : function(data) {
                            alert("设置头图成功");
                        }
                    });
                });
                var img = $('<img style="display:block;width:220px;height:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"/>').attr('src',imgUrl);
                var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:50px;left:190px;cursor:pointer;">X</strong>');
                handler.bindImageDelete(strong, imgId);
                controlsDiv.append(input)
                controlsDiv.append(img);
                controlsDiv.append(strong);
                $(uploadC).append(controlsDiv);
            }
  		});

        imageUploader.bind('UploadComplete', function() {
            iconRoot.hide() ;

            // 如果是上传商家图片需要调用服务器
            if (flag == '4') {
                var sellerImageData = businessAction.getSellerImageData();
                console.log(sellerImageData);
                businessAction.saveSellerImage(sellerImageData);
            }

            alert('上传成功');
        });
  		
  		imageUploader.bind('Error', function(up,err) {
		    alert("文件上传发生错误，请重试!") ;
		});
  		
  		uploadButton.on("click",function(){
			doUploadButt.on("click",function(){
				imageUploader.start() ;
				$(this).unbind("click") ;
			}) ;
		
		}) ;
  		
	};

    // 绑定图片删除动作
    handler.bindImageDelete = function(strong, imgId) {
        strong.on('click', function() { // bind delete action
            $.get(testJybbHost + '/jybb-upload/image2/delete.json?imageId=' + imgId);
            $(this).parent().remove();
        });
    }

    //动态添加图文框
    handler.selectCheckbox=function(){
    	$('.selector').delegate('input','click',function(){
    		var _that=$(this);
    		if(!_that.is(':checked')){
    			//取消勾选后处理的事
    			_that.parents('.changeNum').find('.control-label').each(function(){
    				if(_that.attr("tagName")==$(this).text()){
	    				$(this).parent().remove();
	    			}
    			})
    		}else{
    			//勾选后处理的事
				var controlGroup = $("<div class='control-group' tagId=" + _that.val() + "></div>");
				var label = $('<label class="control-label" for="inputEmail"></label>').text(_that.attr("tagName"));
                controlGroup.append(label);

				var controls = $('<div  class="controls sortable" style="margin-left:190px;"></div>');
				if(_that.parents('.changeNum').attr('changeNumFlag') == '1'){
					//适合、特点的渲染
					controls.attr('id','especiallyC'+_that.val());
					var flagEventA= $('<a class="btn btn-success" id="'+("especially"+_that.val())+'" style="margin-left: 30px; position: relative; z-index: 1;width:80px;">上传图片</a>');
				}else if(_that.parents('.changeNum').attr('changeNumFlag') == '2'){
					//互动项目的渲染
					controls.attr('id','interactionC'+_that.val());
					var flagEventA= $('<a class="btn btn-success" id="'+("interaction"+_that.val())+'" style="margin-left: 30px; position: relative; z-index: 1;width:80px;">上传图片</a>');
					var flagEventInputIAPrice = $('<input id="' + ("interactionPrice"+_that.val()) + '" type="text" style="margin-left:16px;" placeholder="￥该项目费用，不填表示免费"/>');
                    var flagEventInputIARemark = $('<input id="' + ("interactionRemark"+_that.val()) + '" type="text" placeholder="费用备注，如自带装备有折扣"/>');
                    controlGroup.append(flagEventInputIAPrice);
                    controlGroup.append(flagEventInputIARemark);
                    
				}

                controlGroup.append(flagEventA);
				controlGroup.append(controls);
    			_that.parents('.selector').after(controlGroup);

    			//调用图片上传
    			if(_that.parents('.changeNum').attr('changeNumFlag') == '1'){
    				window.server.strategyFile("especially"+_that.val(),"#especiallyC"+_that.val(),'1');
    			}else if(_that.parents('.changeNum').attr('changeNumFlag') == '2'){
    				window.server.strategyFile("interaction"+_that.val(),"#interactionC"+_that.val(),'2');
    			}

    		}
    	})
    }

    handler.selectCheckbox();
	//拖拽插件的调用
	$('.sortable').sortable();
    // 上传特色菜
    window.server.strategyFile('uploadFoodImgBtn',"#uploadFoodImgC","3");
    // 上传景区图片
	window.server.strategyFile('uploadSellerImgBtn',"#uploadSellerImgC","4");
})

